<template>
  <div>
    <el-form :disabled="disableElement" :model="applyFormDatas" :rules="rules" label-width="150px" ref="applyForm"
      style="width: 70%; margin-left: 15%">
      <el-form-item label="申请人" prop="applicant" :disabled="true">
        <el-input v-model="applyFormDatas.applicant" @focus="focus">
          <template slot="append">
            <el-button @click="focus">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="申请部门" prop="applicant_dept">
        <el-input readonly v-model="applyFormDatas.applicant_dept" />
      </el-form-item>
      <el-form-item label="申请机构" prop="applicant_org">
        <el-input readonly v-model="applyFormDatas.applicant_org" />
      </el-form-item>
      <el-form-item label="申请人联系方式" prop="applicant_contact">
        <el-input v-model="applyFormDatas.applicant_contact" />
      </el-form-item>
      <el-form-item label="应用场景" prop="application_business_sys">
        <el-select style="width: 100%" v-model="applyFormDatas.application_business_sys" placeholder="请选择"
          @change="businessSysChange">
          <el-option v-for="(dict, index) in businessSysList" :key="index" :label="dict.dictLabel"
            :value="dict.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="申请数量" prop="apply_amount">
        <el-input v-model="applyFormDatas.apply_amount" />
      </el-form-item>
      <el-form-item label="运营商" prop="operator">
        <el-select style="width: 100%" v-model="applyFormDatas.operator" placeholder="请选择运营商" @change="operatorChanged">
          <el-option v-for="(dict, index) in subOperatorDictList" :key="index" :label="dict.dictLabel"
            :value="dict.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资费套餐" prop="product">
        <el-select style="width: 100%" v-model="applyFormDatas.product" placeholder="请选择资费套餐" @change="productChanged">
          <el-option v-for="(fee, index) in feeList" :key="index" :label="fee.name +
            ' ( ' +
            fee.operatorplatformName +
            ' 价格:' +
            fee.bill +
            '元 数据用量:' +
            fee.flow +
            'MB)'
            " :value="fee.id"></el-option>
        </el-select> 
      </el-form-item>
      <el-form-item label="配送地址" prop="shipping_addr">
        <el-input v-model="applyFormDatas.shipping_addr" @focus="focusAddress">
          <template slot="append">
            <el-button @click="focusAddress">选择</el-button>
          </template>
        </el-input>
        <!--         <el-select
          style="width: 100%"
          filterable
          v-model="applyFormDatas.shipping_addr"
          placeholder="请选择/输入配送地址"
        >
          <el-option
            v-for="(dict, index) in shipping_addrList"
            :key="index"
            :label="dict.address"
            :value="dict.address"
          ></el-option>
        </el-select> -->
      </el-form-item>
      <el-form-item label="需求内容" prop="remark">
        <el-input type="textarea" style="font-size: 12px" :rows="3" placeholder="补充申请需求内容"
          v-model="applyFormDatas.remark" />
      </el-form-item>
      <div v-if="showFormBtn" style="
          width: 30%;
          margin-left: 35%;
          display: flex;
          justify-content: space-between;
        ">
        <el-button type="primary" size="mini" @click="submitForm">提交</el-button>
        <el-button size="mini" @click="resetForm">重置</el-button>
      </div>
    </el-form>
    <!-- 申请人弹窗 -->
    <el-dialog :close-on-click-modal="false" title="申请人" :visible.sync="selectApplicantDiagVisible" width="40%"
      :before-close="AreaClose">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="" prop="userName">
          <el-input v-model="queryParams.userNameselectConfirm" placeholder="用户名或用户姓名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-table ref="businessUserTable" v-loading="loading" :data="businessUserList" highlight-current-row
          @current-change="handleCurrent">
          <el-table-column show-overflow-tooltip prop="userName" label="登录账号" align="left" />
          <el-table-column align="left" show-overflow-tooltip prop="realName" label="姓名" />
          <el-table-column align="left" show-overflow-tooltip prop="parentName" label="机构全称">
            <template slot-scope="scope">
              {{ scope.row.org.fullName }}
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" @pagination="getBusinessUserList" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="selectCancel">取消</el-button>
        <el-button size="mini" type="primary" @click="selectConfirm()">确定</el-button>
      </span>
    </el-dialog>
    <!-- 收货地址弹窗 -->
    <el-dialog :close-on-click-modal="false" title="配送地址" :visible.sync="selectAddressDiagVisible" width="40%"
      :before-close="AddressClose">
      <el-form :model="queryParamsAddress" ref="queryFormAddress" size="small" :inline="true" label-width="68px">
        <el-form-item label="" prop="address">
          <el-input
            v-model="queryParamsAddress.address"
            placeholder="请输入地址"
            clearable
            style="width: 460px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-table ref="addressTable" v-loading="addressLoading" :data="shipping_addrList" highlight-current-row
          @current-change="handleAddressCurrent">
          <el-table-column show-overflow-tooltip prop="address" label="地址" align="left" />
          <el-table-column fixed="right" label="操作" width="180px" align="center">
            <template slot-scope="scope">
              <el-button @click="deleteRow(scope.row)" size="small">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="addressTotal > 0" @pagination="handleGetAddressList" :total="addressTotal"
          :page.sync="queryParamsAddress.pageNum" :limit.sync="queryParamsAddress.pageSize" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="selectAddressCancel">取消</el-button>
        <el-button size="mini" type="primary" @click="selectAddressConfirm()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getOperator,
  listFeeByOperator,
} from "../../../api/system/resource/fee";
import { getDictList, getSuperiorOrganization } from "../../../api/system/org";
import {
  businessUserList,
  isResourceConsumingOrg,
  getAddressList,
  addAddress,
  delAddress,
} from "../../../api/iot/flowable/custom";
import { deepClone } from "../../../utils";
import { getInfo } from "../../../api/login";

export default {
  props: ["applyFormData", "showFormBtn", "disableElement"],
  dicts: [
    "operatorplatform",
    "sim_fee_status",
    "operator",
    "sim_fee_type",
    "org_group",
  ],
  data() {
    return {
      currentUserId: "",
      remark: "补充申请需求内容",
      applyFormDatas: this.applyFormData,
      operatorVo: {
        orgId: "",
        businessSysDictValue: "",
      },
      rules: {
        applicant: [
          {
            required: true,
            message: "申请人不能为空",
            trigger: "blur",
          },
        ],
        applicant_dept: [
          {
            required: true,
            message: "申请部门不能为空",
            trigger: "blur",
          },
        ],
        applicant_org: [
          {
            required: true,
            message: "请选择申请机构",
            trigger: "blur",
          },
        ],
        applicant_contact: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请填入申请人正确手机号",
            trigger: "blur",
          },
        ],
        application_business_sys: [
          {
            required: true,
            message: "应用场景不能为空",
            trigger: "change",
          },
        ],
        apply_amount: [
          {
            pattern: /^[1-9]\d*$/,
            required: true,
            message: "申请数量应为正整数，且不能为空",
            trigger: "blur",
          },
        ],
        operator: [
          {
            required: true,
            message: "运营商不能为空",
            trigger: "blur",
          },
        ],
        sub_operator: [
          {
            required: true,
            message: "运营商平台不能为空",
            trigger: "change",
          },
        ],
        product: [
          {
            required: true,
            message: "资费套餐不能为空",
            trigger: "blur",
          },
        ],
        shipping_addr: [
          {
            required: true,
            message: "配送地址不能为空",
            trigger: "blur",
          },
        ],
        apply_memo: [
          {
            required: true,
            message: "备注不能为空",
            trigger: "blur",
          },
        ],
        CityTelecomApprovalResult: [
          {
            required: true,
            message: "审批结果不能为空",
            trigger: "blur",
          },
        ],
        ipPool: [
          {
            required: true,
            message: "请选择IP池",
            trigger: "blur",
          },
        ],
        APNNames: [
          {
            required: true,
            message: "APN名称不能为空",
            trigger: "blur",
          },
        ],
        CityTelecomApprovalAssignedIP: [
          {
            required: true,
            message: "已分配IP不能为空",
            trigger: "blur",
          },
        ],
        purchaseType: [
          {
            required: true,
            message: "采购方式不能为空",
            trigger: "blur",
          },
        ],
        purchasingPersonnel: [
          {
            required: true,
            message: "指定采购人员不能为空",
            trigger: "blur",
          },
        ],
        SubOperator: [
          {
            required: true,
            message: "运营商平台不能为空",
            trigger: "blur",
          },
        ],
        PurchaseListExcel: [
          {
            required: true,
            message: "采购清单Excel文件必须上传",
            trigger: "blur",
          },
        ],
        PurchaseListScanCopy: [
          {
            required: true,
            message: "盖章采购清单扫描件必须上传",
            trigger: "blur",
          },
        ],
        ShippingInfo: [
          {
            required: true,
            message: "请输入物流单号或者快递单号",
            trigger: "blur",
          },
        ],
        // PurchaseListMemo: [
        //   {
        //     required: true,
        //     message: "备注不能为空",
        //     trigger: "blur",
        //   },
        // ],
        SimCardImportFile: [
          {
            required: true,
            message: "卡入库文件不能为空",
            trigger: "blur",
          },
        ],
        // SimCardImportMemo: [
        //   {
        //     required: true,
        //     message: "备注不能为空",
        //     trigger: "blur",
        //   },
        // ],
        AccountID: [
          {
            required: true,
            message: "账号ID不能为空",
            trigger: "blur",
          },
        ],
        // SimCardImportComment: [
        //   {
        //     required: true,
        //     message: "备注不能为空",
        //     trigger: "blur",
        //   },
        // ],
      },
      subOperatorDictList: [],
      shipping_addrList: [],
      businessSysList: [],
      feeList: [],
      selectApplicantDiagVisible: false,
      selectAddressDiagVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        //deptId: undefined,
        roleId: 10,
      },
      // 收货地址弹窗查询参数
      queryParamsAddress: {
        pageNum: 1,
        pageSize: 10,
        address: "",
        //deptId: undefined,
        roleId: 10,
      },
      selectedUser: {},
      selectedAddress: {},
      total: 0,
      addressTotal: 0,
      businessUserList: [],
      // 遮罩层
      loading: true,
      addressLoading: true,
    };
  },
  created() {
    getDictList("apply_scene").then((res) => {
      this.businessSysList = res.data;
    });

    getDictList("operator").then((res) => {
      this.subOperatorDictList = res.data;
    });

    // console.log("this.orgId："+JSON.stringify(this.applyFormData));
    // listFeeByOperator(this.applyFormDatas.applicant_org,this.applyFormDatas.operator).then((response) => {
    //   this.feeList = response.data;
    // });

    isResourceConsumingOrg().then((res) => {
      if (res.data == 1) {
        //登录账号业务机构是资源使用单位
        getInfo().then((res) => {
          //自动填写当前操作员信息且只读
          const user = res.user;
          this.applyFormData.applicant = user.realName;
          this.applyFormData.applicant_id = user.userId;
          this.applyFormData.applicant_username = user.userName;
          this.applyFormData.applicant_dept = user.org.orgName;
          this.getSuperiorOrg(user.orgId);
          this.applyFormData.applicant_contact = user.phone;
          this.operatorVo.orgId = user.parentId;
          this.pageOrgId = user.org.orgId;
          this.orgIdtow = user.org.orgId;
          this.currentUserId = user.userId;
          getAddressList({ userId: user.userId }).then((res) => {
            this.applyFormDatas.shipping_addr = res.rows[0].address;
          });
        });
      }
    });
  },
  methods: {
    initData() {
      let val = this.applyFormDatas.application_business_sys;
      this.operatorVo.businessSysDictValue = val;
      //TODO DOMTAO 屏蔽多余查询
      // getOperator(this.operatorVo).then((res) => {
      //   this.subOperatorDictList = res.data;
      // });
      // console.log(this.operatorVo.orgId)

      let current = this.applyFormDatas.operator;
      listFeeByOperator( this.operatorVo.orgId,current).then((response) => {
        this.feeList = response.data;
      });
    },
    /*     selectBlur(e) {
      if (e.target.value !== "") {
        this.applyFormDatas.shipping_addr = e.target.value;
        this.$forceUpdate(); // 强制更新
      }
    }, */
    //删除
    deleteRow(row) {
      this.$confirm("确认进行删除操作吗？", "请确认", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        confirmButtonClass: "el-button--primary",
      }).then(() => {
        delAddress(row.id).then((res) => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.selectedAddress = {}
          if(row.address == this.applyFormDatas.shipping_addr){
            this.applyFormDatas.shipping_addr = ''
          }
          this.handleGetAddressList();
        });
      });
    },
    businessSysChange(val) {
      if(!this.operatorVo.orgId){
        this.applyFormDatas.application_business_sys = ''
        this.$message({
          message:'请先填写申请人!',
          type:'warning'
        })
        return
      }
      this.operatorVo.businessSysDictValue = val;
      getOperator(this.operatorVo).then((res) => {
        this.subOperatorDictList = res.data;
      });
      this.applyFormDatas.operator = "";
      this.applyFormDatas.product = "";
      this.feeList = [];
    },
    /** 平台改变获取套餐*/
    operatorChanged(row, defaultValue) {
      if (defaultValue) {
        this.applyFormDatas.product = defaultValue;
      } else {
        this.applyFormDatas.product = "";
      }
      this.$set(this.applyFormDatas, this.applyFormDatas.operator, row);
      this.feeList = [];
      let current = null;
      current = row;
      /*       for (let i = 0; i < this.subOperatorDictList.length; i++) {
        console.log('this.subOperatorDictList[i]',this.subOperatorDictList[i])
        if (this.subOperatorDictList[i].dictValue == row) {
          current = this.subOperatorDictList[i].dictValue;
          break;
        }
      } */
      if (current != null) {
        listFeeByOperator( this.operatorVo.orgId,current).then((response) => {
          this.feeList = response.data;
        });
      }
    },
    /*选中套餐，存储数据*/
    productChanged(row) {
      this.feeList.forEach((item) => {
        if (item.id == row) {
          this.applyFormDatas.subOperatorPlatForm = item.operatorplatformName;
          this.applyFormDatas.operatorPlatform = item.operatorPlatform;
        }
      });
    },
    // 申请部门
    focus() {
      // this.resetForm();
      this.selectApplicantDiagVisible = true;
      this.getBusinessUserList();
    },
    // 收货地址
    focusAddress() {
      // this.resetForm();
      if(!this.applyFormDatas.applicant){
        this.$message({
          message:'请先填写申请人!',
          type:'warning'
        })
        return
      }
      this.selectAddressDiagVisible = true;
      this.handleGetAddressList();
    },
    changeriodl(data, checked, indeterminate) {
      if (checked) {
        if (data.children) {
          this.$refs.dataTree.setChecked(data, false);
          this.$modal.msgError("请选择部门");
          return;
        }
        this.orgName = data.label;
        this.orgId = data.id;
        this.$refs.dataTree.setCheckedKeys([data.id]);
      }
    },
    // 筛选部门
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    Areasure() {
      this.selectApplicantDiagVisible = false;
      this.orgIdtow = this.orgId;
      this.applicant_dept = this.orgName;
      this.getSuperiorOrg(this.orgId);
    },
    AreaClose() {
      this.selectApplicantDiagVisible = false;
    },
    AddressClose() {
      this.selectAddressDiagVisible = false;
    },
    getBusinessUserList() {
      businessUserList(this.queryParams).then((res) => {
        this.businessUserList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    handleGetAddressList() {
      /*       businessUserList(this.queryParams).then((res) => {
        this.businessUserList = res.rows;
        this.total = res.total;
        this.loading = false;
      }); */
      this.queryParamsAddress.address = ''
      getAddressList({ userId: this.currentUserId,...this.queryParamsAddress }).then((res) => {
        this.shipping_addrList = res.rows;
        this.addressTotal = res.total;
        this.addressLoading = false;
      });
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getBusinessUserList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      if(!this.queryParamsAddress.address){
        this.$message({
          message:'请先填写地址!',
          type:'warning'
        })
        return
      }
      addAddress({
        userId: this.currentUserId,
        address: this.queryParamsAddress.address,
      }).then((res) => {
        this.$message.success("操作成功");
        this.queryParamsAddress.pageNum = 1;
        this.handleGetAddressList();
      });
    },
    /** 关闭申请人选择弹窗 */
    selectCancel() {
      this.selectApplicantDiagVisible = false;
    },
    /** 关闭地址选择弹窗 */
    selectAddressCancel() {
      this.selectAddressDiagVisible = false;
    },
    /** 申请人选择弹窗 */
    handleCurrent(val) {
      if (val) {
        this.currentUserId = val.userId;
        this.selectedUser = val;
        this.$refs.applyForm.clearValidate("applicant");
        this.$refs.applyForm.clearValidate("applicant_org");
        this.$refs.applyForm.clearValidate("applicant_dept");
      }
    },
    /** 地址选择弹窗 */
    handleAddressCurrent(val) {
      if (val) {
        this.selectedAddress = val;
        this.$refs.applyForm.clearValidate("shipping_addr");
      }
    },
    /** 确认选择申请人 */
    selectConfirm() {
      if (this.selectedUser.userName) {
        this.applyFormDatas.applicant_username = this.selectedUser.userName;
        this.applyFormDatas.applicant = this.selectedUser.realName;
        this.applyFormDatas.applicant_id = this.selectedUser.userId;
        this.getSuperiorOrg(this.selectedUser.orgId);
        this.applyFormDatas.applicant_contact = this.selectedUser.phone;
        this.applyFormDatas.applicant_dept = this.selectedUser.org.orgName;
        this.operatorVo.orgId = this.selectedUser.parentId;
        this.selectApplicantDiagVisible = false;
        getAddressList({ userId: this.currentUserId }).then((res) => {
          this.shipping_addrList = res.rows;
          this.addressTotal = res.total;
          if (res.rows[0]) {
            this.applyFormDatas.shipping_addr = res.rows[0].address;
          } else {
            this.applyFormDatas.shipping_addr = "";
          }
        });
      } else {
        this.$message.error("请选择申请人");
      }
    },
    /** 确认选择地址 */
    selectAddressConfirm() {
      if (this.selectedAddress.address) {
        this.applyFormDatas.shipping_addr = this.selectedAddress.address;
        this.selectAddressDiagVisible = false;
      } else {
        this.$message.error("请选择地址");
      }
    },

    getSuperiorOrg(id) {
      getSuperiorOrganization(id).then((res) => {
        this.applyFormDatas.applicant_org = res.data.name;
      });
    },

    /** 清空表单 */
    resetForm() {
      //请空数据
      this.applyFormDatas = {
        applicant: "",
        applicant_username: "",
        applicant_id: "",
        applicant_dept: "",
        applicant_org: "",
        applicant_contact: "",
        application_business_sys: "",
        apply_amount: "",
        sub_operator: "",
        product: "",
        shipping_addr: "",
        apply_comment: "",
        remark: "",
      };
      this.feeList = [];
      this.subOperatorDictList = [];
      //this.$refs.applyForm.clearValidate();
      /*       this.applyForm = {
        applicant: "",
        applicant_dept: "",
        applicant_org: "",
        applicant_contact: "",
        application_business_sys: "",
        apply_amount: "",
        sub_operator: "",
        product: "",
        shipping_addr: "",
      }; */
    },
    submitForm() {
      this.$refs.applyForm.validate((valid) => {
        if (!valid) return false;
        // 触发sumit事件
        const params = {
          formType: "ApplyForm",
          formData: this.applyFormDatas,
        };
        this.$emit("submit", params);
        return true;
      });
    },
  },
};
</script>
<style scoped>
::v-deep .el-table__fixed-right {
  height: 100% !important;
}
</style>
